package com.chapter.sample.redis.controller;

import com.chapter.sample.redis.cache.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class JHSProductController {
    public static final String JHS_KEY = "jhs";
    public static final String JHS_KEY_A = "jhs:a";
    public static final String JHS_KEY_B = "jhs:b";


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询：在高并发的情况下，只能走redis查询，走db的话必定会把db打垮
     * “聚划算”分页案例，每次1页，每页5条显示
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/product/find")
    public List<Product> find(int page, int size) {
        List<Product> list = null;

        long start = (page - 1) * size;
        long end = start + size - 1;

        try {
            //采用redis list结构里面的lrange命令来实现加载和分页查询
            list = redisTemplate.opsForList().range(JHS_KEY, start, end);
            if (CollectionUtils.isEmpty(list)) {
                //TODO 走MySQL查询

                return null;
            }
        } catch (Exception e) {
            //出现了异常，一般redis宕机了，或者redis网络抖动导致timeout
            log.error("jhs exception:{}", e);
            e.printStackTrace();
        }
        return list;
    }

    //AB双缓存架构，防止热点key突然失效
    @RequestMapping("/product/findB")
    public List<Product> findB(int page, int size) {
        List<Product> list = null;

        long start = (page - 1) * size;
        long end = start + size - 1;

        try {
            //采用redis list结构里面的lrange命令来实现加载和分页查询
            list = redisTemplate.opsForList().range(JHS_KEY_A, start, end);
            if (CollectionUtils.isEmpty(list)) {
                log.info("---A缓存已经过期失效或活动已经结束了，记得人工修改，B缓存继续顶着");
                list = redisTemplate.opsForList().range(JHS_KEY_B, start, end);
                //TODO 走MySQL查询
                if (CollectionUtils.isEmpty(list)) {
                    log.info("缓存击穿了，需要走DB......");
                }
                return null;
            }
            log.info("参加活动的商家！");
        } catch (Exception e) {
            //出现了异常，一般redis宕机了，或者redis网络抖动导致timeout
            log.error("jhs exception:{}", e);
            e.printStackTrace();
        }
        return list;
    }
}
